<!-- views/admin/creativeAchievement.vue -->
<template>
  <!-- 搜索区域 -->
  <div class="container" style="margin-top: 30px">
    <el-row :gutter="20">
      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" 
                v-show="showSearch" label-width="73px">
          <el-form-item label="成果名称" prop="nameKeyword">
            <el-input v-model="queryParams.nameKeyword" placeholder="请输入成果名称"
                      clearable style="width: 200px" @keyup.enter="handleQuery"/>
          </el-form-item>

          <el-form-item label="类别" prop="categoryKeyword">
            <el-select  v-model="queryParams.categoryKeyword" placeholder="请选择类别"
              clearable style="width: 200px">
              <el-option label="文旅部" value="文旅部"/>
              <el-option label="教育部" value="教育部"/>
              <el-option label="教育厅" value="教育厅"/>
              <el-option label="教育局" value="教育局"/>
              <el-option label="市级文体旅局" value="市级文体旅局"/>
              <el-option label="省级文旅厅" value="省级文旅厅"/>
              <el-option label="省级文联" value="省级文联"/>
              <el-option label="中国文联" value="中国文联"/>
              <el-option label="市文联主办的市级年度展演" value="市文联主办的市级年度展演"/>
              <el-option label="省体育局及其下属各协会或学会主办的省级年度展演" 
                        value="省体育局及其下属各协会或学会主办的省级年度展演"/>
              <el-option label="国家体育总局及其下属各协会权威行业协会或学会主办的全国年度展演" 
                        value="国家体育总局及其下属各协会权威行业协会或学会主办的全国年度展演"/>
              <el-option label="国家体育总局及其下属各协会权威行业协会或学会主办的一般性全国年度展演" 
                        value="国家体育总局及其下属各协会权威行业协会或学会主办的一般性全国年度展演"/>
              <el-option label="其他" value="其他"/>
            </el-select>
          </el-form-item>

          <el-form-item label="级别" prop="levelKeyword">
            <el-select v-model="queryParams.levelKeyword" placeholder="请选择级别"
              clearable style="width: 200px">
              <el-option label="一等奖" value="一等奖"/>
              <el-option label="二等奖" value="二等奖"/>
              <el-option label="三等奖" value="三等奖"/>
              <el-option label="优秀奖" value="优秀奖"/>
              <el-option label="入选奖" value="入选奖"/>
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="Search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>



    <!-- 操作按钮区域 -->
    <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" size="mini" @click="handleAdd">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="EditPen" size="mini" :disabled="single"  @click="handleUpdate" >修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" size="mini" :disabled="multiple" @click="handleDelete">删除</el-button>
          </el-col>
        </el-row>
      </el-col>
    </el-row>
      

    <!-- 数据表格 -->
    <el-table :data="tableData" border style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="creativeId" label="ID" width="90" />
      <el-table-column prop="username" label="姓名" width="130"/>
      <el-table-column prop="creativeAchievementName" label="成果名称" width="250" />
      <el-table-column prop="creativeCategory" label="类别" width="250" />
      <el-table-column prop="creativeLevel" label="级别" width="250" />
      <el-table-column prop="creativeScore" label="分值" width="150" />
      <el-table-column prop="creativeNotes" label="备注" width="270" />
    </el-table>

    <!-- 新增对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="38%">
      <el-form ref="formRef" :model="formData" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="姓名" prop="username" required>
              <el-input v-model="formData.username" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="成果名称" prop="creativeAchievementName" required>
              <el-input v-model="formData.creativeAchievementName" placeholder="请输入成果名称" />
            </el-form-item>
          </el-col>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="类别" prop="creativeCategory" required>
                <el-select v-model="formData.creativeCategory" placeholder="请选择类别">
                  <el-option label="文旅部" value="文旅部"></el-option>
                  <el-option label="教育部" value="教育部"></el-option>
                  <el-option label="教育厅" value="教育厅"></el-option>
                  <el-option label="教育局" value="教育局"></el-option>
                  <el-option label="市级文体旅局" value="市级文体旅局"></el-option>
                  <el-option label="省级文旅厅" value="省级文旅厅"></el-option>
                  <el-option label="省级文联" value="省级文联"></el-option>
                  <el-option label="中国文联" value="中国文联"></el-option>
                  <el-option label="市文联主办的市级年度展演" value="市文联主办的市级年度展演"></el-option>
                  <el-option label="省体育局及其下属各协会或学会主办的省级年度展演" value="省体育局及其下属各协会或学会主办的省级年度展演"></el-option>
                  <el-option label="国家体育总局及其下属各协会权威行业协会或学会主办的全国年度展演" value="国家体育总局及其下属各协会权威行业协会或学会主办的全国年度展演"></el-option>
                  <el-option label="国家体育总局及其下属各协会权威行业协会或学会主办的一般性全国年度展演" value="国家体育总局及其下属各协会权威行业协会或学会主办的一般性全国年度展演"></el-option>
                  <el-option label="其他" value="其他"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="级别" prop="creativeLevel" required>
                <el-select v-model="formData.creativeLevel" placeholder="请选择级别">
                  <el-option label="一等奖" value="一等奖"></el-option>
                  <el-option label="二等奖" value="二等奖"></el-option>
                  <el-option label="三等奖" value="三等奖"></el-option>
                  <el-option label="优秀奖" value="优秀奖"></el-option>
                  <el-option label="入选奖" value="入选奖"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="分值" prop="creativeScore" required>
                <el-input-number v-model="formData.creativeScore" :min="0" :step="1" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注" prop="creativeNotes">
                <el-input v-model="formData.creativeNotes" type="textarea" placeholder="请填写内容" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-row>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 分页组件 -->
    <Pagination v-model="queryParams" :total="total" @change="handleChange" />
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue';
import { listCreative, delCreative, addCreative, updateCreative } from "@/api/creativeAchievement";
import { ElMessage, ElMessageBox } from 'element-plus';
import Pagination from '@/components/Pagination/index.vue';


const tableData = ref([]); // 初始化为响应式数组
const total = ref(0);
const selectedRow = ref([]);//处理选中行
const single = ref(true);
const multiple = ref(true);

// 查询参数
const queryParams = ref({
  nameKeyword: '',
  categoryKeyword: '',
  levelKeyword: '',
  currentPage: 1,
  pageSize: 10,
});

// 对话框相关变量
const dialogVisible = ref(false);
const dialogTitle = ref('新增创作成果');
const formData = reactive({
  creativeId: null,
  username: '',
  creativeAchievementName: '',
  creativeCategory: '',
  creativeLevel: '',
  creativeScore: 0,
  creativeNotes: ''
});




// 控制显示/隐藏搜索表单
const showSearch = ref(true);

// 查询方法
async function handleQuery() {
  try {
    const response = await listCreative({
      nameKeyword: queryParams.value.nameKeyword,
      categoryKeyword: queryParams.value.categoryKeyword,
      levelKeyword: queryParams.value.levelKeyword,
      currentPage: queryParams.value.currentPage,// 分页从1开始
      pageSize: queryParams.value.pageSize
    });
    
    tableData.value = response.data.data;// 更新表格数据
    total.value = response.data.total;// 总条目数
    console.log('查询结果:', response.data);
  } catch (error) {
    console.error('查询失败:', error);
    ElMessage.error('数据加载失败');
  }
}

// 重置查询条件
function resetQuery() {
  queryParams.value = {
    nameKeyword: '',
    categoryKeyword: '',
    levelKeyword: '',
    currentPage: 1,
    pageSize: 10
  };
  handleQuery();// 重置后重新查询
}

// 显示新增对话框
function handleAdd() {
  Object.assign(formData, {
    creativeId: null,
    username: '',
    creativeAchievementName: '',
    creativeCategory: '',
    creativeLevel: '',
    creativeScore: 0,
    creativeNotes: ''
  });
  dialogTitle.value = '新增创作成果'; 
  dialogVisible.value = true;
}

// 提交表单到后端
async function handleSubmit() {
  try {
    const isUpdate = !!formData.creativeId; 
    const apiMethod = isUpdate ? 
      () => updateCreative(formData.creativeId, formData) : 
      () => addCreative(formData);
    await apiMethod();
    ElMessage.success(isUpdate ? '修改成功' : '新增成功');
    dialogVisible.value = false;
    await handleQuery();
  } catch (error) {
    ElMessage.error(`操作失败: ${error.response?.data?.message || error.message}`);
  }
}

// 表格选择处理
function handleSelectionChange(selection) {
  selectedRow.value = selection;
  single.value = selection.length !== 1;  // 修改按钮状态
  multiple.value = selection.length === 0; // 删除按钮状态
}

// 修改操作
async function handleUpdate() {
  if (selectedRow.value.length !== 1) { 
    ElMessage.error('请选择且仅选择一条记录进行修改');
    return;
  }
  const row = selectedRow.value[0];
  Object.assign(formData, row);
  dialogTitle.value = '修改创作成果'; 
  dialogVisible.value = true;
}

// 删除操作
async function handleDelete() {
  const selectedIds = selectedRow.value.map(row => row.creativeId);
  if (selectedIds.length === 0) {
    ElMessage.error('请选择要删除的记录');
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确认删除选中的${selectedIds.length}条创作成果吗？`, 
      '警告',
      { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
    );

    await delCreative(selectedIds); 
    ElMessage.success('删除成功');
    
    await handleQuery();
    selectedRow.value = []; // 清空选中状态
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(`删除失败: ${error.response?.data?.message || error.message}`);
    }
  }
}

// 分页处理
const handleChange = (newPage, newPageSize) => {
  queryParams.value.currentPage = newPage;
  queryParams.value.pageSize = newPageSize;
  handleQuery();
};

// 页面加载时自动查询一次
onMounted(() => {
  handleQuery();
});
</script>

<style scoped>
.el-input__inner {
  margin-left: 2px;
}
</style>
